﻿using iText.Kernel.Font;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Kernel.Pdf.Canvas.Parser;
using iText.Kernel.Utils;
using NPOI.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;

namespace Cyss.Core.Helper
{
    /// <summary>
    /// pdf帮助类
    /// </summary>
    public class PDFHelper
    {

        /// <summary>
        /// 合并PDF
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        public static byte[] MergePdfFiles(byte[][] files)
        {
            return MergePdfFiles(files.Select(x => x.ToStream()).ToArray());
        }

        /// <summary>
        /// 合并PDF
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        public static byte[] MergePdfFiles(Stream[] files)
        {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();//构建字节输出流
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(stream));
            PdfMerger merger = new PdfMerger(pdfDoc);
            foreach (var file in files)
            {
                //PdfMerger merger = new PdfMerger(pdfDoc);
                PdfDocument newDoc = new PdfDocument(new PdfReader(file));
                merger.Merge(newDoc, 1, newDoc.GetNumberOfPages());
                newDoc.Close();
            };
            pdfDoc.Close();
            return stream.ToByteArray();
        }

        /// <summary>
        ///  旋转PDF
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="rotate"></param>
        /// <returns></returns>
        public static byte[] Rotate(byte[] bytes, int rotate = 90)
        {
            return Rotate(bytes.ToStream(), rotate);
        }

        /// <summary>
        /// 旋转PDF
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="Rotate"></param>
        /// <returns></returns>
        public static byte[] Rotate(Stream stream, int Rotate = 90)
        {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();//构建字节输出流
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(stream), new PdfWriter(outputStream));
            for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++)
            {
                PdfPage page = pdfDoc.GetPage(i);
                page.SetRotation(Rotate);
            }
            pdfDoc.Close();
            return outputStream.ToArray();
        }

        /// <summary>
        /// 将多页pdf拆分成单页
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static List<byte[]> SplitPage(byte[] bytes)
        {
            return SplitPage(bytes.ToStream());
        }
        /// <summary>
        /// 将多页pdf拆分成单页
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static List<byte[]> SplitPage(Stream stream)
        {
            List<byte[]> bys = new List<byte[]>();
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(stream));
            for (int pageIndex = 1; pageIndex <= pdfDoc.GetNumberOfPages(); pageIndex++)
            {
                PdfPage page = pdfDoc.GetPage(pageIndex);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();//构建字节输出流
                PdfDocument newPdfDoc = new PdfDocument(new PdfWriter(baos));
                newPdfDoc.AddPage(page.CopyTo(newPdfDoc));
                newPdfDoc.Close();
                bys.Add(baos.ToByteArray());
            }
            pdfDoc.Close();
            pdfDoc = null;
            return bys;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static DataTable GetDataTable(byte[] bytes)
        {
            return GetDataTable(bytes.ToStream());
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static DataTable GetDataTable(Stream stream)
        {
            var strs = GetStrings(stream);
            DataTable dt = new DataTable();
            dt.Columns.Add("col1", typeof(string));
            foreach (var str in strs)
            {
                DataRow dr = dt.NewRow();
                dr[0] = str;
                dt.Rows.Add(dr);
            }
            return dt;
        }

        /// <summary>
        /// 将pdf的文字转换成一个text;然后返回一个datatable
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static IList<string> GetStrings(byte[] bytes)
        {
            return GetStrings(bytes.ToStream());
        }
        /// <summary>
        /// 将pdf的文字转换成一个text;然后返回一个datatable
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static IList<string> GetStrings(Stream stream)
        {
            string Strtext;
            try
            {
                PdfDocument pdfDoc = new PdfDocument(new PdfReader(stream));
                int numberOfPages = pdfDoc.GetNumberOfPages();

                StringBuilder text = new StringBuilder();
                for (int i = 1; i <= numberOfPages; i++)
                {
                    text.Append(PdfTextExtractor.GetTextFromPage(pdfDoc.GetPage(i)));
                }
                pdfDoc.Close();
                Strtext = text.ToString();
            }
            catch (Exception ex)
            {
                return null;
            }
            if (string.IsNullOrEmpty(Strtext))
            {
                return null;
            }
            return Strtext.Split('\n', StringSplitOptions.RemoveEmptyEntries);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="text"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="rotation"></param>
        /// <param name="fontName"></param>
        /// <param name="fontSzie"></param>
        /// <returns></returns>
        public static byte[] PdfWriteText(byte[] bytes, string text, float x, float y, float rotation, string fontName = "Futura", float fontSzie = 12f)
        {
            return PdfWriteText(bytes.ToStream(), text, x, y, rotation, fontName, fontSzie);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="text"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="rotation"></param>
        /// <param name="fontName"></param>
        /// <param name="fontSzie"></param>
        /// <returns></returns>
        public static byte[] PdfWriteText(Stream stream, string text, float x, float y, float rotation, string fontName = "Futura", float fontSzie = 12f)
        {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(stream), new PdfWriter(outStream));

            PdfCanvas canvas = new PdfCanvas(pdfDoc.GetFirstPage());
            canvas.BeginText()
                .SetFontAndSize(PdfFontFactory.CreateFont(fontName), 12)
                .MoveText(x, y)
                .ShowText(text)
                .EndText();
            return outStream.ToByteArray();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="llx"></param>
        /// <param name="lly"></param>
        /// <param name="urx"></param>
        /// <param name="ury"></param>
        /// <returns></returns>
        public static byte[] ManipulatePdf(byte[] bytes, float llx, float lly, float urx, float ury)
        {
            return ManipulatePdf(bytes.ToStream(), llx, lly, urx, ury);
        }

        /// <summary>
        /// 剪切pdf
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="llx"></param>
        /// <param name="lly"></param>
        /// <param name="urx"></param>
        /// <param name="ury"></param>
        /// <returns></returns>
        public static byte[] ManipulatePdf(Stream stream, float llx, float lly, float urx, float ury)
        {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(stream), new PdfWriter(outStream));
            
            int numberOfPages = pdfDoc.GetNumberOfPages();
            iText.Kernel.Geom.Rectangle newMediaBox = new iText.Kernel.Geom.Rectangle(llx, lly, urx, ury);
            for (int i = 1; i <= numberOfPages; i++)
            {
                var page = pdfDoc.GetPage(i);
                page.SetMediaBox(newMediaBox);
            }
            pdfDoc.Close();
            return outStream.ToByteArray();
        }

      
    }
}